/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.cdtour.controller;


import com.dmgis.entity.DmMapRectangle;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.DZWarning;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.HXYJ_Warning;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TourStations;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TourTravelPath;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.businessservice.yyhx.service.IFirefcstService;
import com.dmgis.qxfw.dataservice.businessservice.yyly.service.IForestryfcstService;
import com.dmgis.qxfw.dataservice.businessservice.yysl.service.IWaternfoService;
import com.dmgis.qxfw.dataservice.businessservice.cdtour.service.ITourInfoSearchService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.weblib.MapCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.Map.Entry;

/**
 * This class is used for 景区相关信息查询
 *
 * @author dsq
 * @version 1.0, 2018年8月21日 上午10:37:45
 */
@Controller
@RequestMapping("/xttour")
public class TourInfoSearchController {
    private  final String operatingSystem;

    @Autowired
    public TourInfoSearchController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }


    @Resource
    ITourInfoSearchService tourService;
    @Resource
    private IWaternfoService forecastInfoService;
    @Resource
    private IForestryfcstService forestryfcstService;
    @Resource
    private IFirefcstService firefcstService;
    @Resource
    private IQxInfoService qxInfoService;
    @Resource
    private ITransformService transformService;

    // MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();



    /**
     * 初始化城镇预报界面信息
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/initTourPage")
    @ResponseBody
    public Object initTourPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        ForecastKey newestDate = tourService.getTownNewDate();
        // 加载列表
        String timechar = newestDate.getTimeChar();
        String datechar = new DateTime(newestDate.getDateChar()).toDateString();
        arrayList.add(timechar);
        arrayList.add(datechar);
        return arrayList;
    }

    @RequestMapping("/checklogin")
    @ResponseBody
    public boolean checklogin(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        HttpSession session = request.getSession();
        // 拦截其他行业气象的controller层，如disaster等
        // 放行登陆
        if (session.getAttribute("userName") != null) {
            // 登录成功不拦截
            return true;
        }
        return false;
    }

    @RequestMapping("/getTourFcst")
    @ResponseBody
    public Object getTourFcst(HttpServletRequest request, Model model) throws Exception {
        ForecastKey selectKey = new ForecastKey();// 查询类
        String time = request.getParameter("date");// 时间
        String sc = request.getParameter("sc");// 时次
        String sx = request.getParameter("sx");// 时效
        String cityId = request.getParameter("cityId");// 城市
        String stationid = request.getParameter("stationid");// 站点编号
        String type = request.getParameter("type");
        String strStationID = "";
        String strCountyName = "";
        int nTimes=0;
        List<TourFcstInfo> resultList = new ArrayList<TourFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {
            if (!StringUtil.IsNullOrEmpty(sx)) {
                nTimes = Integer.parseInt(sx);
            }
            if (!(cityId == null) && !cityId.equals("")) {
                selectKey.setStationID(cityId);// 站点号
            }
            selectKey.setNTimes(nTimes);
            selectKey.setTimeChar(sc);
            selectKey.setStationID(stationid);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            selectKey.setForecasttype(type);
            List<tour_fcst> fcstList = tourService.getTourFcstInfo(selectKey);

            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 2) {
                strStationID = fcstList.get(i).getStationid();
                strCountyName = fcstList.get(i).getStationname();
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindd().toString().replace("-65535", "0").trim());
                String windV12 =  wcd.GetWeatherFs(String
                        .valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(fcstList.get(i).getWinds()))));
                String windV24 =  wcd.GetWeatherFs(String
                        .valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(fcstList.get(i + 1).getWinds()))));
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "转" + windV24;
                }
                double maxTemp = fcstList.get(i).getMaxtemp() > fcstList.get(i + 1).getMaxtemp()
                        ? fcstList.get(i).getMaxtemp() : fcstList.get(i + 1).getMaxtemp();
                double minTemp = fcstList.get(i).getMintemp() > fcstList.get(i + 1).getMintemp()
                        ? fcstList.get(i + 1).getMintemp() : fcstList.get(i).getMintemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                TourFcstInfo fcstInfo = new TourFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                DmMapPoint dmDot = new DmMapPoint(fcstList.get(i).getLongitude(), fcstList.get(i).getLatitude());
                DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                fcstInfo.setY(ltDot.y);
                fcstInfo.setX(ltDot.x);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                String weather = "";
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather = fcstList.get(i).getWeather1().trim();
                } else {
                    weather = fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            // TODO: 查询异常
            e.printStackTrace();
        }
        return resultList;
    }

    @RequestMapping("/getTourStation")
    @ResponseBody
    public Object getTourStation(HttpServletRequest request, Model model) {
        List<TourStations> resultList = new ArrayList<TourStations>();
        try {
            List<tour_stations> result = tourService.getTourStation();

            int count = result.toArray().length;
            for (int i = 0; i < count; i++) {
                TourStations tour = new TourStations();
                tour.setStationname(result.get(i).getStationname());
                tour.setLatitude(result.get(i).getLatitude());
                tour.setLongitude(result.get(i).getLongitude());
                tour.setLat(result.get(i).getLatitude());
                tour.setLon(result.get(i).getLongitude());
                DmMapPoint dmDot = new DmMapPoint(result.get(i).getLongitude(), result.get(i).getLatitude());
                DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                tour.setY(ltDot.y);
                tour.setX(ltDot.x);
                resultList.add(tour);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    /**
     * 获取气象台发布的预警信号
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月19日
     */
    @RequestMapping("/showWarning")
    @ResponseBody
    public Object showWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getWarningInfo(startDate, endDate, -1);// 查询时间段内的预警信息号
    }


    @RequestMapping("/inittourdz")
    @ResponseBody
    public Object initDZQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(tourService.getDZNewDate());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }


    @RequestMapping("/initsightpoint")
    @ResponseBody
    public Object initsightpoint() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(tourService.getsightpoint());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }

    @RequestMapping("/initscenery")
    @ResponseBody
    public Object initscenery() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(tourService.getsceneryDate());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }

    @RequestMapping("/initslhxwaring")
    @ResponseBody
    public Object initslhxwaring() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(tourService.initslhxwaring());
        result.add(endDate.AddDays(-7).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }

    @RequestMapping("/showDzWarning")
    @ResponseBody
    public Object showDzWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getTouristProduct(-1, "景点地质灾害预报", startDate, endDate);// 查询地质灾害
    }
    //城头山地质灾害
    @RequestMapping("/showDzCtsWarning")
    @ResponseBody
    public Object showDzCtsWarnishowZhiShuInfong(HttpServletRequest request, Model model) {
        try{
        }catch (Exception e) {
            System.err.println(e.getStackTrace());
        }
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<cts_dzwarning> result = new ArrayList<cts_dzwarning>();
        List<cts_dzwarning> resultList = new ArrayList<cts_dzwarning>();
        result=tourService.getTouristCtsProduct(-1, "景点地质灾害预报", startDate, endDate);// 查询地质灾害
        for (cts_dzwarning cts_dzwarning : result) {
            cts_dzwarning result1 = new cts_dzwarning();
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(cts_dzwarning.getPos())) {
                String[] posArr = cts_dzwarning.getPos().split("\\*");
                boolean isOn = false;
                if(isOn){
                    continue;
                }
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        String[] strdata = pos.split("#")[1].replace(" ", ",").split(",");

                        int ii = 0;
                        double xval = 0.0;
                        double yval = 0.0;
                        Integer index = 0;
                        DmMapPoint[] dt = new DmMapPoint[strdata.length/2];
                        for (int i = 0; i < strdata.length / 2; i++) {
                            xval = Double.parseDouble(strdata[2 * i]);
                            yval = Double.parseDouble(strdata[2 * i + 1]);
                            DmMapPoint DmDot1 = new DmMapPoint(xval, yval);
                            dt[index] = DmDot1;
                            index++;
                            ii++;
                        }

                        DmMapPoint dmDotJW = new DmMapPoint(111.667149, 29.684678);
                        DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                        if (!isOn) {
                            MapCommon dmMapCom = new MapCommon();
                            if(dmMapCom.pointWithinPolygon(Arrays.asList(dt),dmDotLb.x,dmDotLb.y)){
                                isOn = true;
                                result1.setId(cts_dzwarning.getId());
                                result1.setProductname(cts_dzwarning.getProductname());
                                result1.setProducttype(cts_dzwarning.getProducttype());
                                result1.setForecasttime(cts_dzwarning.getForecasttime());
                                result1.setMaketime(cts_dzwarning.getMaketime());
                                result1.setMaker(cts_dzwarning.getMaker());
                                result1.setBindid(cts_dzwarning.getBindid());
                                resultList.add(result1);
                            }
                        }
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
            }
            }
            return resultList;
    }

    @RequestMapping("/showDzpart")
    @ResponseBody
    public Object showDzpart(HttpServletRequest request, Model model) {
        String bindid = request.getParameter("bindid");
        List<DZWarning> result = new ArrayList<DZWarning>();
        if (!bindid.equals("")) {
            result = tourService.getDzpart(bindid);// 查询地质灾害预警区
        }
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }
            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
        }
        return result;
    }

    @RequestMapping("/showDZpoint")
    @ResponseBody
    public Object showDZpoint(HttpServletRequest request, Model model) {
        String result = "[";
        List<tour_stations> tourStations = tourService.getTourStation();
        String poss = request.getParameter("pos");// 坐标

        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<String> dpoint = new ArrayList<String>();
        String stanames = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }

                for (tour_stations tour : tourStations) {
                    DmMapPoint dmDotJW = new DmMapPoint(tour.getLongitude(), tour.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    MapCommon dmMapCom = new MapCommon();
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotLb.x,dmDotLb.y)){
                        if (!tour.getDisasterids().equals("")) {
                            String[] point = tour.getDisasterids().split(";");
                            for (int i = 0; i < point.length; i++) {
                                if (!dpoint.contains(point[i])) {
                                    dpoint.add(point[i]);
                                }
                            }
                        }
                        if (!stanames.contains(tour.getStationname())) {
                            stanames += tour.getStationname();
                            result += "{";
                            result += "\"tourname\":\"" + tour.getStationname() + "\",";
                            result += "\"grade\":\"" + tour.getGrade() + "\",";
                            result += "\"people\":\"" + tour.getPeople() + "\",";
                            result += "\"phone\":\"" + tour.getPeople() + "\",";
                            result += "\"disasterscale\":\"" + "" + "\",";
                            result += "\"intime\":\"" + "" + "\",";
                            result += "\"firsttime\":\"" + "" + "\",";
                            result += "\"disType\":\"" + "" + "\",";
                            result += "\"disName\":\"" + tour.getStationname() + "\",";
                            result += "\"threatproperty\":\"" + "" + "\",";
                            result += "\"threathouseholds\":\"" + "" + "\",";
                            result += "\"nextdefendmeasures\":\"" + "" + "\",";
                            result += "\"monitorperson\":\"" + "" + "\",";
                            result += "\"tel\":\"" + "" + "\",";
                            result += "\"monitorprincipal\":\"" + "" + "\",";
                            result += "\"monitorprincipaltel\":\"" + "" + "\",";
                            result += "\"motiondir\":\"" + "" + "\",";
                            result += "\"lon\":" + tour.getLongitude() + ",";
                            result += "\"lat\":" + tour.getLatitude() + "";
                            result += "},";
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<potential_points> resultList = new ArrayList<potential_points>();
        if (dpoint != null && dpoint.size() > 0) {
            resultList = tourService.getDisPoint(dpoint);
        }
        for (potential_points city : resultList) {
            Double lon = Double.parseDouble(city.getLon().toString());
            Double lat = Double.parseDouble(city.getLat().toString());
            result += "{";
            result += "\"tourname\":\"" + "" + "\",";
            result += "\"grade\":\"" + "" + "\",";
            result += "\"people\":\"" + "" + "\",";
            result += "\"phone\":\"" + "" + "\",";
            result += "\"disasterscale\":\"" + city.getDis_scale() + "\",";
            result += "\"disType\":\"" + city.getDis_type() + "\",";
            result += "\"disName\":\"" + city.getPp_name() + "\",";
            result += "\"threatproperty\":\"" + city.getThreat_pop() + "\",";
            result += "\"threathouseholds\":\"" + city.getThreat_prop() + "\",";
            result += "\"monitorperson\":\"" + city.getContact() + "\",";
            result += "\"tel\":\"" + city.getContact_tel() + "\",";
            result += "\"monitorprincipal\":\"" + city.getContact1() + "\",";
            result += "\"monitorprincipaltel\":\"" + city.getContact1_tel() + "\",";
            result += "\"lon\":" + lon + ",";
            result += "\"lat\":" + lat + "";
            result += "},";
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    @RequestMapping("/showSlhxWarning")
    @ResponseBody
    public Object showSlhxWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getTouristProduct(-1, "景点森林火险预报", startDate, endDate);//
    }

    @RequestMapping("/showSlhxCtsWarning")
    @ResponseBody
    public Object showSlhxCtsWarning(HttpServletRequest request, Model model) {
        try{
        }catch (Exception e) {
            System.err.println(e.getStackTrace());
        }
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<cts_dzwarning> result = new ArrayList<cts_dzwarning>(); //
        List<cts_dzwarning> resultList = new ArrayList<cts_dzwarning>();
        result=tourService.getSlhxCtsProduct(-1, "景点森林火险预报", startDate, endDate);//
        for (cts_dzwarning cts_dzwarning : result) {
            cts_dzwarning result1 = new cts_dzwarning();
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(cts_dzwarning.getPos())) {
                String[] posArr = cts_dzwarning.getPos().split("\\*");
                boolean isOn = false;
                if(isOn){
                    continue;
                }
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
//                        Se_dtstj dst1 = new Se_dtstj();
                        String[] strdata = pos.split("#")[1].replace(" ",",").split(",");
                        Integer index = 0;
                        DmMapPoint[] dt = new DmMapPoint[strdata.length/2];
                        int ii = 0;
                        double xval = 0.0;
                        double yval = 0.0;
                        for (int i = 0; i < strdata.length / 2; i++) {
                            xval = Double.parseDouble(strdata[2 * i]);
                            yval = Double.parseDouble(strdata[2 * i + 1]);
                            DmMapPoint DmDot1 = new DmMapPoint(xval, yval);
                            dt[index] = DmDot1;
                            index++;
                            ii++;
                        }
                        DmMapPoint dmDotJW = new DmMapPoint(111.667149, 29.684678);
                        DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                        if(!isOn){
                            MapCommon dmMapCom = new MapCommon();
                            if(dmMapCom.pointWithinPolygon(Arrays.asList(dt),dmDotLb.x,dmDotLb.y)){
                                isOn = true;
                                result1.setId(cts_dzwarning.getId());
                                result1.setProductname(cts_dzwarning.getProductname());
                                result1.setProducttype(cts_dzwarning.getProducttype());
                                result1.setForecasttime(cts_dzwarning.getForecasttime());
                                result1.setMaketime(cts_dzwarning.getMaketime());
                                result1.setMaker(cts_dzwarning.getMaker());
                                result1.setBindid(cts_dzwarning.getBindid());
                                resultList.add(result1);
                            }
                        }
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
            }
        }
        return resultList;
    }

    @RequestMapping("/showFirepart")
    @ResponseBody
    public Object showFirepart(HttpServletRequest request, Model model) throws Exception {
        String bindid = request.getParameter("bindid");
        FireSearch selectKey = new FireSearch();// 查询类
        List<Warning> resultList = new ArrayList<Warning>();// 主

        List<HXYJ_Warning> result = new ArrayList<HXYJ_Warning>(); //
        if (!bindid.equals("")) {
            selectKey.setDocid(bindid);
            result = forestryfcstService.getFirewarning(selectKey);// 查询森林火险预警区
        }
        String time = "";
        for (HXYJ_Warning warning : result) {
            if (warning.getGradeArea2() != null && !warning.getGradeArea2().equals("")) {
                warning.setWarntype("蓝色预警");
            }
            if (warning.getGradeArea3() != null && !warning.getGradeArea3().equals("")) {
                warning.setWarntype("黄色预警");
            }
            if (warning.getGradeArea4() != null && !warning.getGradeArea4().equals("")) {
                warning.setWarntype("橙色预警");
            }
            if (warning.getGradeArea5() != null && !warning.getGradeArea5().equals("")) {
                warning.setWarntype("红色预警");
            }
            ArrayList<Entites> entites = new ArrayList<Entites>();
            time = warning.getDateChar().toString();
            Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(time);
            // 格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String sDate = sdf.format(date);// 时间

            if (!StringUtil.IsNullOrEmpty(warning.getPos())) {
                String[] posArr = warning.getPos().split("\\*");
                DmMapPoint[] points = null;
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entites entity = new Entites();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        entity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        points = new DmMapPoint[dotset.length];
                        Integer index = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            points[index] = dmDot;
                            index++;
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                Warning nwarning = new Warning();// 总
                nwarning.setGradeArea3(warning.getGradeArea3());
                nwarning.setGradeArea4(warning.getGradeArea4());
                nwarning.setGradeArea5(warning.getGradeArea5());
                nwarning.setWarntype(warning.getWarntype());
                nwarning.setDocpath(warning.getDocpath());
                nwarning.setDateChar(sDate);
                nwarning.setDocid(warning.getDocid());
                nwarning.setEntites(entites);
                nwarning.setDpart(points);
                nwarning.setPos(warning.getPos());
                resultList.add(nwarning);
            }
        }
        return resultList;
    }

    @RequestMapping("/showHXpoint")
    @ResponseBody
    public Object showHXpoint(HttpServletRequest request, Model model) {
        String result = "[";
        List<tour_stations> tourStations = tourService.getTourStation();
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<String> dpoint = new ArrayList<String>();
        String stanames = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String color = pos.split("#")[0];
                String Warntype = "";
                if (color.equals("65535")) {
                    Warntype = "黄色";
                } else if (color.equals("255")) {
                    Warntype = "黄色";
                } else if (color.equals("42495")) {
                    Warntype = "橙色";
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    points[index] = dmDot;
                    index++;
                }
                for (tour_stations tour : tourStations) {
                    DmMapPoint dmDotJW = new DmMapPoint(tour.getLongitude(), tour.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    MapCommon dmMapCom = new MapCommon();
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotLb.x,dmDotLb.y)){
                        if (!tour.getDisasterids().equals("")) {
                            String[] point = tour.getDisasterids().split(";");
                            for (int i = 0; i < point.length; i++) {
                                if (!dpoint.contains(point[i])) {
                                    dpoint.add(point[i]);
                                }
                            }
                        }
                        if (!stanames.contains(tour.getStationname())) {
                            stanames += tour.getStationname();
                            result += "{";
                            result += "\"stationname\":\"" + tour.getStationname() + "\",";
                            result += "\"warngrade\":\"" + Warntype + "\",";
                            result += "\"grade\":\"" + tour.getGrade() + "\",";
                            result += "\"people\":\"" + tour.getPeople() + "\",";
                            result += "\"phone\":\"" + tour.getPeople() + "\",";
                            result += "\"lon\":" + tour.getLongitude() + ",";
                            result += "\"lat\":" + tour.getLatitude() + "";
                            result += "},";
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    @RequestMapping("/showCityWarning")
    @ResponseBody
    public Object showCityWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getTouristProduct(-1, "景点城市火险预报", startDate, endDate);//
    }

    @RequestMapping("/showSightPointWeather")
    @ResponseBody
    public Object showSightPointWeather(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getTouristProduct(-1, "景点预报", startDate, endDate);// 查询时间段内的景点预报
    }

    @RequestMapping("/showSightWeather")
    @ResponseBody
    public Object showSightWeather(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getTouristProduct(-1, "景观预报", startDate, endDate);// 查询时间段内的景观预报
    }

    /**
     * 初始化指数界面
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/initZhiShuPage")
    @ResponseBody
    public Object initZhiShuPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        ForecastKey newestDate = tourService.getZhiShuNewestDate();
        String stationid = "";
        List<tour_stations> dataList = tourService.getAllTourStations(stationid);
        // 加载列表
        String timechar = newestDate.getTimeChar();
        String datechar = new DateTime(newestDate.getDateChar()).toDateString();
        Map<String, String> zs = DbConfig.getZhiShuType();
        Iterator<Entry<String, String>> iterator = zs.entrySet().iterator();
        Entry<String, String> entry;
        List<String> zhishus = new ArrayList<String>();
        while (iterator.hasNext()) {
            entry = iterator.next();
            String zhishu = entry.getValue();
            zhishus.add(zhishu);
        }
        arrayList.add(timechar);
        datechar="2024-04-01";
        arrayList.add(datechar);
        arrayList.add(dataList);
        arrayList.add(zhishus);
        return arrayList;
    }

    /**
     * 指数预报展示
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年8月23日
     */
    @RequestMapping("/showZhiShuInfo")
    @ResponseBody
    public Object showZhiShuInfo(HttpServletRequest request, Model model) {
        String result = "";
        Map<String, String> zs = DbConfig.getZhiShuType();
        ForecastKey selectKey = new ForecastKey();// 查询类
        String time = request.getParameter("date");// 时间
        String sc = request.getParameter("sc");// 时次
        String county = request.getParameter("county");// 区县
        String tourname = request.getParameter("tourname");// 景区
        String index = request.getParameter("index");// 指数
        try {
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            selectKey.setCounty(county);
            selectKey.setTourname(tourname);
            List<Map<String, Object>> resultList = tourService.getZhiShuInfo(selectKey);
            if (index.equals("")) {
                String dtime = new DateTime(selectKey.getDateChar()).toDateTimeString("yyyy年MM月dd日") + sc + "指数预报";
                result = "<p class='intitle'><span>" + dtime
                        + "</span></p><div class='textinfo'><table class='ybcontent'>";
                StringBuilder cont = new StringBuilder();
                for (Map<String, Object> map : resultList) {
                    cont.append("<tr valign='top'><td class='ybtitle' >" + map.get("cityname").toString().trim()
                            + "</td></tr>");
                    Iterator<Entry<String, String>> iterator = zs.entrySet().iterator();
                    Entry<String, String> entry;
                    while (iterator.hasNext()) {
                        entry = iterator.next();
                        String zhishu = entry.getValue();
                        String key = entry.getKey();
                        String level = map.get(key + "grade").toString();
                        String note = map.get(key + "text").toString();
                        cont.append("<tr valign='top'>");
                        cont.append(
                                "<td width='200px'><div class='zhishurow'><div class='zhishuimg'><img src='"+DbConfig.IP+"cddmgisqxfwweb/CDTourWeb/images/zhishu/"
                              //本地
//                                "<td width='200px'><div class='zhishurow'><div class='zhishuimg'><img src='/images/zhishu/"
                                        + zhishu + ".png'alt=''/></div>");
                        cont.append("<div class='zhishucont'><div class='zhishulevel'>" + zhishu + "：" + level
                                + "</div><div class='zhishunote'>" + note + "</div></div></div></td></tr>");
                    }
                }
                result += cont.toString() + "</table></div>";
            } else {
                result = "[";
                for (Map<String, Object> map : resultList) {
                    Iterator<Entry<String, String>> iterator = zs.entrySet().iterator();
                    Entry<String, String> entry;
                    while (iterator.hasNext()) {
                        entry = iterator.next();
                        String zhishu = entry.getValue();
                        if (zhishu.equals(index)) {
                            String key = entry.getKey();
                            String level = map.get(key + "grade").toString();
                            String note = map.get(key + "text").toString();
                            result += "{";
                            result += "\"id\":\"" + map.get("id") + "\",";
                            result += "\"cityid\":\"" + map.get("cityid") + "\",";
                            result += "\"stationname\":\"" + map.get("cityname") + "\",";
                            result += "\"datechar\":\"" + map.get("datechar") + "\",";
                            result += "\"timechar\":\"" + map.get("timechar") + "\",";
                            result += "\"level\":\"" + level + "\",";
                            result += "\"note\":\"" + note + "\",";
                            result += "\"lon\":" + map.get("longitude") + ",";
                            result += "\"lat\":" + map.get("latitude") + "";
                            result += "},";
                        }
                    }
                }
                if (result.endsWith(",")) {
                    result = result.substring(0, result.length() - 1);
                }
                result = result + "]";
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }

    @RequestMapping("/showDoc")
    @ResponseBody
    public String showDoc(HttpServletRequest request, Model model) {
        String servicePath = "";
        String docId = request.getParameter("docId");// 文档编号
        String fileName = request.getParameter("docName");// 文档名称
        String tableName = request.getParameter("tableName");
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\warning\\";
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String docType = fileName.split("\\.")[fileName.split("\\.").length - 1];
        // 判断文件类型是否是word
        if (docType.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(docType, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "\\Temp\\warning\\" + fileName.replace(docType, "pdf");
                servicePath = basePath+servicePath;
            } else {
                // 从mongdo中获取文件
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", docId);
                map.put("table_name", tableName);
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                // 本地文件
                try {
                    servicePath = "\\Temp\\warning\\" + fileName.replace(docType, "pdf");
                    servicePath = basePath+servicePath;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    @RequestMapping("/showTxt")
    @ResponseBody
    public String showTxt(HttpServletRequest request, Model model) {
        // 处理txt文件
        String result = "";
        String txtId = request.getParameter("txtId");// 文档编号
        String fileName = request.getParameter("txtName");// 文档名称
        String tableName = request.getParameter("tableName");

        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\warning\\";
        }else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/warning/";
        }


        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String txtType = fileName.split("\\.")[fileName.split("\\.").length - 1];
        // 判断文件类型是否是word
        if (txtType.equals("txt")) {
            String txtPath = urlpath + fileName;
            File txtFile = new File(txtPath);
            if (txtFile.exists()) {
                result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
            } else {
                // 从mongdo中获取文件
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", txtId);
                map.put("table_name", tableName);
                map.put("collectionName", "txt_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                if (data == null) {
                    return "";
                }
                // 下载doc文件
                FileUtil.bytesToFile(data, txtPath);
                result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
            }
        }
        return result;
    }

    @RequestMapping("showActualImg")
    @ResponseBody
    public Object showActualImg(HttpServletRequest request, Model model) throws Exception {
        String stationid = request.getParameter("stationid");
        List<TourStation> resultList = new ArrayList<TourStation>();
        List<tour_stations> dataList = tourService.getAllTourStations(stationid);
        List<tour_actual_img> actual_imgs = tourService.getNewestActualImg();
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\actualImg\\";
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/actualImg/";
        }


        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        // 处理得到最新图片
        for (tour_stations station : dataList) {
            for (tour_actual_img actualImg : actual_imgs) {
                if (station.getStationid().equals(actualImg.getStationid())) {
                    // 获取最新的图片
                    String fileName = station.getStationname() + ".jpg";
                    if (!new File(urlpath + fileName).exists()) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", station.getStationid());
                        map.put("collectionName", "image_file");
                        map.put("advCode", DbConfig.advCode);
                        map.put("table_name","tour_actual_img");
                        byte[] data = ms.selectData(map);
                        if (data == null) {
                            return null;
                        }
                        String localPath = urlpath + fileName;
                        FileUtil.bytesToFile(data, localPath);
                    }
                    // 赋值
                    TourStation tourStation = new TourStation();
                    tourStation.setStationId(station.getStationid());
                    tourStation.setStationName(station.getStationname());
                    tourStation.setAlti(station.getAltitude());
                    tourStation.setLon(station.getLongitude());
                    tourStation.setLat(station.getLatitude());
                    if (station.getLongitude() != null && station.getLatitude() != null) {
                        DmMapPoint dmDot = new DmMapPoint(station.getLongitude(), station.getLatitude());
                        DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                        tourStation.setY(ltDot.y);
                        tourStation.setX(ltDot.x);
                    }
                    tourStation.setGrade(station.getGrade());
                    tourStation.setAreaName(station.getAreaname());
                    tourStation.setDateChar(actualImg.getDatechar());
                    tourStation.setImageName(actualImg.getImagename());
                    if (operatingSystem.equals("Windows")){
                        tourStation.setImagePath("Temp\\actualImg\\" + fileName);
                    }else {
                        tourStation.setImagePath("Temp/actualImg/" + fileName);
                    }

                    tourStation.setText(station.getText());
                    tourStation.setPeople(station.getPeople());
                    tourStation.setPhone(station.getPhone());
                    tourStation.setLocation(station.getLocation());
                    tourStation.setSuggest(station.getSuggest());
                    resultList.add(tourStation);
                }
            }
        }
        return resultList;
    }


    @RequestMapping("/initActualImgGallery")
    @ResponseBody
    public Object initActualImgGallery(HttpServletRequest request, Model model) {
        return tourService.getAllTourStations("");
    }


    @RequestMapping("/getImgGallery")
    @ResponseBody
    public Object getImgGallery(HttpServletRequest request, Model model) {
        String stationId = request.getParameter("station");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<tour_actual_img> resultList = tourService.getImgGallery(startDate + ":00:00", endDate + ":00:00",
                stationId);
        // 处理得到图片
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\actualImg\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        // 处理得到最新图片
        for (tour_actual_img actualImg : resultList) {
            String fileName = actualImg.getStationname() + ".jpg";
            if (!new File(urlpath + fileName).exists()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("stationid", actualImg.getStationid());
                map.put("datechar", actualImg.getDatechar());
                map.put("collectionName", "tour_actual_img");
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                String localPath = urlpath + fileName;
                FileUtil.bytesToFile(data, localPath);
            }
            actualImg.setImagename("Temp\\actualImg\\" + fileName);
        }
        return resultList;
    }

    @RequestMapping("showTourImg")
    @ResponseBody
    public Object showTourImg(HttpServletRequest request, Model model) throws Exception {
        List<TourStation> resultList = new ArrayList<TourStation>();
        String stationid = "";
        List<tour_stations> dataList = tourService.getAllTourStations(stationid);
        String urlpath;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\TourImg\\";
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/TourImg/";
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String path = "";
        // 处理得到最新图片
        for (tour_stations station : dataList) {

            String fileName = station.getStationname() + ".jpg";
            if (!new File(urlpath + fileName).exists()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("stationid", station.getStationid());
                map.put("collectionName", "image_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    path = "images/nopic.jpg";
                } else {
                    String localPath = urlpath + fileName;
                    FileUtil.bytesToFile(data, localPath);
                    path = null;
                }
            } else {
                path = null;
            }
            // 赋值
            TourStation tourStation = new TourStation();
            tourStation.setStationId(station.getStationid());
            tourStation.setStationName(station.getStationname());
            tourStation.setAlti(station.getAltitude());
            tourStation.setLon(station.getLongitude());
            tourStation.setLat(station.getLatitude());
            if (station.getLongitude() != null && station.getLatitude() != null) {
                DmMapPoint dmDot = new DmMapPoint(station.getLongitude(), station.getLatitude());
                DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
                tourStation.setY(ltDot.y);
                tourStation.setX(ltDot.x);
            }
            tourStation.setGrade(station.getGrade());
            tourStation.setAreaName(station.getAreaname());
            if (StringUtil.IsNullOrEmpty(path)) {
                if (operatingSystem.equals("Windows")){
                    tourStation.setImagePath("Temp\\TourImg\\" + fileName);
                }else {
                    tourStation.setImagePath("Temp/TourImg/" + fileName);
                }

            } else {
                tourStation.setImagePath(path);
            }
            tourStation.setText(station.getText().replace("\r", "\\r").replace("\n", "\\n"));
            tourStation.setPeople(station.getPeople());
            tourStation.setPhone(station.getPhone());
            tourStation.setLocation(station.getLocation());
            tourStation.setSuggest(station.getSuggest());
            resultList.add(tourStation);

        }
        return resultList;
    }

    @RequestMapping("/updatePoint")
    @ResponseBody
    public Object updatePoint(HttpServletRequest request, Model model) {
        tour_stations selecttour = new tour_stations();
        String tourname = request.getParameter("tourname");
        String address = request.getParameter("address");
        String grade = request.getParameter("grade");
        String phone = request.getParameter("phone");
        String people = request.getParameter("people");
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String product = request.getParameter("product");
        selecttour.setStationname(tourname);
        selecttour.setLocation(address);
        selecttour.setGrade(grade);
        selecttour.setPhone(phone);
        selecttour.setPeople(people);
        if (lon != null && lon.length() > 0) {
            selecttour.setLongitude(Double.parseDouble(lon));
        }
        if (lat != null && lat.length() > 0) {
            selecttour.setLatitude(Double.parseDouble(lat));
        }
        selecttour.setText(product);
        String stationid = tourService.getstationid(selecttour);
        String resultList = tourService.updatePoint(selecttour, stationid);
        return resultList;
    }

    @RequestMapping("/addPoint")
    @ResponseBody
    public Object addPoint(HttpServletRequest request, Model model) {
        tour_stations selecttour = new tour_stations();
        String tourname = request.getParameter("tourname");
        String address = request.getParameter("address");
        String areaname = request.getParameter("areaname");
        String grade = request.getParameter("grade");
        String phone = request.getParameter("phone");
        String people = request.getParameter("people");
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String product = request.getParameter("product");
        selecttour.setStationname(tourname);
        selecttour.setLocation(address);
        selecttour.setAreaname(areaname);
        selecttour.setGrade(grade);
        selecttour.setPhone(phone);
        selecttour.setPeople(people);
        selecttour.setLongitude(Double.parseDouble(lon));
        selecttour.setLatitude(Double.parseDouble(lat));
        selecttour.setText(product);
        String resultList = tourService.addPoint(selecttour);
        return resultList;
    }

    @RequestMapping("/deletePoint")
    @ResponseBody
    public Object deletePoint(HttpServletRequest request, Model model) {
        tour_stations selecttour = new tour_stations();
        String tourname = request.getParameter("tourname");
        selecttour.setStationname(tourname);
        String resultList = tourService.deletePoint(selecttour);
        return resultList;
    }

    @RequestMapping("/uploadImg")
    @ResponseBody
    public String uploadPicture(HttpServletRequest request) throws UnsupportedEncodingException {
        String stationid = request.getParameter("stationid");

        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\TourImg\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);

        String flag = "0";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (request instanceof MultipartHttpServletRequest) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            // 检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request) && iter.hasNext()) {
                // 获取multiRequest 中所有的文件名
                while (iter.hasNext()) {
                    // 一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        String fileName = file.getOriginalFilename();
                        String imgPath = urlpath + fileName;// 本地路径
                        File localFile = new File(imgPath);
                        if (localFile.exists()) {
                            flag = "请不要重复提交，存在同名文件";
                        } else {
                            try {
                                // 入库mongo数据库
                                byte[] bytes = file.getBytes();
                                Map<String,Object> map = new HashMap<>();
                                map.put("collectionName","image_file");
                                map.put("collectionN","image_file");
                                map.put("id",stationid);
                                map.put("advCode",DbConfig.advCode);
                                map.put("table_name","vistor_upload_pic");
                                map.put("data",bytes);
                                int result = ms.insertData(map);
                                file.transferTo(localFile);
                                if (result==1) {
                                    System.out.println("data was updated");
                                    flag = "Temp\\TourImg\\" + fileName;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return flag;
    }

    @RequestMapping("/pathfcst")
    @ResponseBody
    public Object showpathfcst(HttpServletRequest request, Model model) throws Exception {


        // 从请求参数中获取预测类型（如"花卉观赏气象"）
        String fcst = request.getParameter("fcst");
// String fcst = "花卉观赏气象"; // 测试用固定值

// 初始化结果列表和JSON字符串
        List<travel_predict> resultlist = new ArrayList<travel_predict>();
        resultlist = tourService.getTourfcst(fcst); // 获取旅游预测基础数据

        String result = "["; // 开始构建JSON数组

// 处理查询结果
        if (resultlist != null && resultlist.size() > 0) {
            for (travel_predict travel : resultlist) {
                // 获取当前月份用于季节匹配
                Integer fixtime = DateTime.now().GetMonth();
                System.out.println(fixtime); // 调试输出当前月份

                // 处理景点开放时间范围（格式如"3-5"表示3月到5月）
                String[] t = new String[2];
                System.out.println(travel.getTime()); // 调试输出时间范围

                if (travel.getTime().contains("-")) {
                    t = travel.getTime().split("-"); // 拆分开始月和结束月
                    System.out.println(t[0]+","+t[1]); // 调试输出拆分结果
                }
                // 检查当前月份是否在景点推荐时间段内
                if (fixtime > Integer.parseInt(t[0]) && fixtime < Integer.parseInt(t[1])) {
                    // 准备天气预报查询条件
                    ForecastKey selectKey = new ForecastKey(); // 创建查询条件对象

                    // 从请求参数获取时间相关参数
                    String time = request.getParameter("date"); // 预报日期
                    // String time ="2024-12-28"; // 测试用固定值
                    String sc = request.getParameter("sc"); // 预报时次（如"08"）
                    // String sc = "08"; // 测试用固定值
                    String sx = request.getParameter("sx"); // 预报时效（小时）
                    // String sx = "168"; // 测试用固定值

                    // 处理预报时效参数
                    Integer nTimes = null;
                    if(sx!=null){
                        nTimes = Integer.parseInt(sx);
                    }else {
                        System.out.println("异常：sx==null"); // 参数缺失警告
                    }

                    // 设置查询条件
                    selectKey.setNTimes(nTimes);
                    selectKey.setTimeChar(sc);
                    if(time!=null){
                        selectKey.setDateChar(DateTime.parseDate(time).toDate()); // 日期转换
                    }else {
                        System.out.println("异常：time==null"); // 参数缺失警告
                    }

                    // 设置景点信息和预报类型
                    selectKey.setTourname(travel.getJqname()); // 景区名称
                    selectKey.setForecasttype("12"); // 固定预报类型

                    // 执行天气预报查询
                    List<tour_fcst> fcstList = tourService.getTourFcstInfo(selectKey);
                    System.out.println(fcstList.size()); // 调试输出查询结果数量

                    // 处理天气预报数据
                    if (fcstList != null && fcstList.size() > 0) {
                        // 初始化气象要素极值
                        Double maxtemp = 0.0;
                        Double mintemp = 0.0;
                        Double minrain = 0.0;
                        Double maxrain = 0.0;
                        Double minwind = 0.0;
                        Double maxwind = 0.0;
                        String weather = "";

                        // 每两个预报时段为一组进行处理（通常表示白天和夜间）
                        for (int tt = 0; tt < fcstList.size(); tt += 2) {
                            // 计算降水量范围
                            if (fcstList.get(tt).getRain() > fcstList.get(tt + 1).getRain()) {
                                minrain = fcstList.get(tt + 1).getRain();
                                maxrain = fcstList.get(tt).getRain();
                            } else {
                                maxrain = fcstList.get(tt + 1).getRain();
                                minrain = fcstList.get(tt).getRain();
                            }

                            // 计算温度极值
                            if (fcstList.get(tt).getMintemp() > fcstList.get(tt + 1).getMintemp()) {
                                mintemp = fcstList.get(tt + 1).getMintemp();
                            } else {
                                mintemp = fcstList.get(tt).getMintemp();
                            }
                            if (fcstList.get(tt).getMaxtemp() > fcstList.get(tt + 1).getMaxtemp()) {
                                maxtemp = fcstList.get(tt).getMaxtemp();
                            } else {
                                maxtemp = fcstList.get(tt + 1).getMaxtemp();
                            }

                            // 计算风速范围
                            if (Double.parseDouble(fcstList.get(tt).getWinds()) > Double
                                    .parseDouble(fcstList.get(tt + 1).getWinds())) {
                                minwind = Double.parseDouble(fcstList.get(tt + 1).getWinds());
                                maxwind = Double.parseDouble(fcstList.get(tt).getWinds());
                            } else {
                                minwind = Double.parseDouble(fcstList.get(tt).getWinds());
                                maxwind = Double.parseDouble(fcstList.get(tt + 1).getWinds());
                            }

                            // 处理天气现象描述
                            if (fcstList.get(tt).getWeather1().trim()
                                    .equals(fcstList.get(tt + 1).getWeather1().trim())) {
                                weather = fcstList.get(tt).getWeather1().trim(); // 相同天气
                            } else {
                                weather = fcstList.get(tt).getWeather1().trim() + "转"
                                        + fcstList.get(tt + 1).getWeather1().trim(); // 天气转变
                            }
                        }

                        // 检查气象条件是否适合旅游（在推荐参数范围内）
                        if (minrain >= travel.getRainmin() && maxrain <= travel.getRainmax()
                                && mintemp >= travel.getTempmin() && maxtemp <= travel.getTempmax()
                                && minwind >= travel.getWindmin() && maxwind <= travel.getWindmax()) {

                            // 构建JSON格式的推荐结果
                            result += "{";
                            result += "\"stationName\":\"" + travel.getJqname() + "\","; // 景区名称
                            result += "\"spotName\":\"" + travel.getSpotname() + "\","; // 景点名称
                            result += "\"fix\":\"" + "适宜（天气:" + weather + ";温度：" + maxtemp
                                    + "℃;风速：" + maxwind + "m/s）" + "\""; // 推荐理由
                            result += "},";
                        }
                    }
                }
            }
        }

// 处理JSON格式（移除最后一个逗号）
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }

// 完成JSON数组构建
        result = result + "]";
        return result;

    }

    @RequestMapping("/bestpath")
    @ResponseBody
    public Object bestpath(HttpServletRequest request, Model model) throws Exception {
        String tournames = request.getParameter("tournames");
        String tourname = request.getParameter("tourname");
        String[] names = tournames.split(",");
        Double lon = 0.0;
        Double lat = 0.0;
        List<String> stationnames = new ArrayList<String>();
        Map<String, Double[]> map = new HashMap<String, Double[]>();
        Map<String, Double[]> resultD = new LinkedHashMap<String, Double[]>();
        List<TourTravelPath> path = new ArrayList<TourTravelPath>();
        if (!tournames.equals("")) {
            for (int i = 0; i < names.length; i++) {
                stationnames.add(names[i]);
            }
        }
        List<tour_stations> fcstList = tourService.getTourSta(stationnames);
        if (fcstList != null && fcstList.size() > 0) {
            for (tour_stations tour : fcstList) {
                Double[] lonlat = new Double[2];
                if (!tourname.contains(tour.getStationname())) {
                    lonlat[0] = tour.getLongitude();
                    lonlat[1] = tour.getLatitude();
                    map.put(tour.getStationname(), lonlat);
                } else {
                    lon = tour.getLongitude();
                    lat = tour.getLatitude();
                    lonlat[0] = lon;
                    lonlat[1] = lat;
                    resultD.put(tourname, lonlat);
                }
            }
        }
        for (int i = 0; i < fcstList.size(); i++) {
            String nextname = "";
            Point2D pointQD = new Point2D.Double(lon, lat);
            Double distance = Double.MAX_VALUE;
            for (Entry<String, Double[]> m : map.entrySet()) {
                Point2D pointZD = new Point2D.Double(m.getValue()[0], m.getValue()[1]);
                if (getDistance(pointQD, pointZD) < distance) {
                    distance = getDistance(pointQD, pointZD);
                    nextname = m.getKey();
                    lon = m.getValue()[0];
                    lat = m.getValue()[1];
                }
            }
            if (!map.isEmpty()) {
                Double[] lonlat = new Double[2];
                lonlat[0] = lon;
                lonlat[1] = lat;
                resultD.put(nextname, lonlat);
                // 移除已计算的项
                Set<?> mapset = map.entrySet();
                Iterator<?> iterator = mapset.iterator();
                while (iterator.hasNext()) {
                    @SuppressWarnings("rawtypes")
                    Entry mapEntry = (Entry) iterator.next();
                    String key = mapEntry.getKey().toString();
                    if (key.equals(nextname)) {
                        iterator.remove();
                    }
                }
            }
        }
        List<ArrayList<MyPoint>> list = new ArrayList<ArrayList<MyPoint>>();
        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
        for (Entry<String, Double[]> m : resultD.entrySet()) {
            MyPoint point = new MyPoint(m.getValue()[0], m.getValue()[1]);
            tempPos.add(point);
        }
        list.add(tempPos);
        for (Entry<String, Double[]> m : resultD.entrySet()) {
            TourTravelPath p = new TourTravelPath();
            p.setName(m.getKey());
            p.setLon(m.getValue()[0]);
            p.setLat(m.getValue()[1]);
            p.setPos(list);
            p.setPosArr(tempPos);
            path.add(p);
        }
        return path;
    }

    @RequestMapping("/tqbestpath")
    @ResponseBody
    public Object tqbestpath(HttpServletRequest request, Model model) throws Exception {
        String tournames = request.getParameter("tournames");
        String time = request.getParameter("date");// 时间
        String sc = request.getParameter("sc");// 时次
        String sx = request.getParameter("sx");// 时效
        String[] names = tournames.split(",");
        List<String> stationnames = new ArrayList<String>();
        for (int i = 0; i < names.length; i++) {
            stationnames.add(names[i]);
        }
        List<tour_fcst> fcstList = tourService.getTourPathfcst(stationnames, time, sc, sx);

        String strStationID = "";
        String strCountyName = "";
        WebCtrlData wcd = new WebCtrlData();
        List<TourFcstInfo> resultList = new ArrayList<TourFcstInfo>();
        int count = fcstList.toArray().length;
        for (int i = 0; i < count; i += 2) {
            strStationID = fcstList.get(i).getStationid();
            strCountyName = fcstList.get(i).getStationname();
            String windD = "";// 风向信息
            String windV = "";// 风速信息
            String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
            String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindd().toString().replace("-65535", "0").trim());
            String windV12 =  wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(fcstList.get(i).getWinds()))));
            String windV24 =  wcd.GetWeatherFs(String
                    .valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(fcstList.get(i + 1).getWinds()))));
            if (windD12.equals(windD24)) {
                windD += windD12;
            } else {
                windD += windD12 + "转" + windD24;
            }
            if (windV12.equals(windV24)) {
                windV += windV12;
            } else {
                windV += windV12 + "转" + windV24;
            }
            double maxTemp = fcstList.get(i).getMaxtemp() > fcstList.get(i + 1).getMaxtemp()
                    ? fcstList.get(i).getMaxtemp() : fcstList.get(i + 1).getMaxtemp();
            double minTemp = fcstList.get(i).getMintemp() > fcstList.get(i + 1).getMintemp()
                    ? fcstList.get(i + 1).getMintemp() : fcstList.get(i).getMintemp();
            String pic1 = String.format("%02d",
                    Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
            String pic2 = String.format("%02d",
                    Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
            TourFcstInfo fcstInfo = new TourFcstInfo();
            fcstInfo.setStationId(strStationID);
            fcstInfo.setStationName(strCountyName);
            fcstInfo.setMinTemp(minTemp);
            fcstInfo.setMaxTemp(maxTemp);
            fcstInfo.setRain(fcstList.get(i).getRain());
            fcstInfo.setWindD(windD);
            fcstInfo.setWindV(windV);
            fcstInfo.setPic1(pic1);
            fcstInfo.setPic2(pic2);
            fcstInfo.setLat(fcstList.get(i).getLatitude());
            fcstInfo.setLon(fcstList.get(i).getLongitude());
            DmMapPoint dmDot = new DmMapPoint(fcstList.get(i).getLongitude(), fcstList.get(i).getLatitude());
            DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
            fcstInfo.setY(ltDot.y);
            fcstInfo.setX(ltDot.x);
            fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
            fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
            String weather = "";
            if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                weather = fcstList.get(i).getWeather1().trim();
            } else {
                weather = fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
            }
            fcstInfo.setWeather(weather);
            fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
            resultList.add(fcstInfo);
        }
        return resultList;
    }

    /**
     * 初始化火险指数
     */
    @RequestMapping("/initjdcshxPage")
    @ResponseBody
    public Object initcshxPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        cshx_zsyb newestDate = tourService.initcshxPage();
        // 加载列表
        String forcastdate = new DateTime(newestDate.getForcastdate()).toDateString();
        arrayList.add(forcastdate);
        return arrayList;
    }

    /**
     * 获取时间点的指数查看
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getCFireIndex")
    @ResponseBody
    public Object getFireIndex(HttpServletRequest request, Model model) throws ParseException {
        String date = request.getParameter("date");
        List<cshx_zsyb> resultList = tourService.getFireIndex(date);
        for (cshx_zsyb zsyb : resultList) {
            zsyb.setDate(new DateTime(zsyb.getForcastdate()).toDateString());
            List<tour_stations> result = tourService.getImpdot(zsyb.getStationname());
            String names = "";// 名称
            String principals = "";// 负责人
            String tels = "";// 联系电话
            for (tour_stations dot : result) {
                names += dot.getStationname() + ",";
                principals += dot.getPeople() + ",";
                tels += dot.getPhone() + ",";
            }
            if (!StringUtil.IsNullOrEmpty(names)) {
                names = names.substring(0, names.length() - 1);
                principals = principals.substring(0, principals.length() - 1);
                tels = tels.substring(0, tels.length() - 1);
            }
            zsyb.setName(names);
            zsyb.setPrincipal(principals);
            zsyb.setTel(tels);
        }
        return resultList;
    }

    /**
     * 景点地质灾害、森林火险
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getJDWarning")
    @ResponseBody
    public Object getJDWarning(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        String industrytype = request.getParameter("industrytype");
        List<industry_warning> resultList = tourService.getJDWarning(type, industrytype);
        ArrayList list = new ArrayList();
        String result = "";
        if (resultList != null && resultList.size() > 0) {
            result += resultList.get(0).getDatechar().substring(0, 10) + " ";
            if (!StringUtil.IsNullOrEmpty(resultList.get(0).getGradearea5())) {
                result += "风险很高：" + resultList.get(0).getGradearea5() + " ";
            } else if (!StringUtil.IsNullOrEmpty(resultList.get(0).getGradearea4())) {
                result += "风险高：" + resultList.get(0).getGradearea4() + " ";
            } else if (!StringUtil.IsNullOrEmpty(resultList.get(0).getGradearea3())) {
                result += "风险较高：" + resultList.get(0).getGradearea3();
            }
            list.add(result);
            list.add(resultList.get(0).getWarningid());
        }
        return list;
    }
@RequestMapping("/getWarningPatrtInfo")
@ResponseBody
public Object getWarningInfo() throws Exception {
 List<Object>  resultList =   tourService.getWarningPatrtInfo();
    HashMap<String, Object> map = new HashMap<>();
    map.put("data",resultList);
    map.put("size",resultList.size());
    return map ;
}

    @RequestMapping("/showWarningpart")
    @ResponseBody
    public Object showWarningpart(HttpServletRequest request, Model model) throws Exception {
        String bindid = request.getParameter("bindid");
        List<Warning> resultList = new ArrayList<Warning>();// 主
        FireSearch selectKey = new FireSearch();// 查询类
        String type = request.getParameter("type");
        if (type.equals("气象预警")) {
            List<warning> result = new ArrayList<warning>();
            if (!bindid.equals("")) {
                result = tourService.getQxpart(bindid);// 查询气象预警区
            }
            for (warning warn : result) {
                ArrayList<Entites> entites = new ArrayList<Entites>();
                Double lon = 0.0;
                Double lat = 0.0;
                if (!StringUtil.IsNullOrEmpty(warn.getPos())) {
                    String[] posArr = warn.getPos().split("\\*");
                    for (String pos : posArr) {
                        try {
                            if (pos == null || pos.equals("")) {
                                continue;
                            }
                            Entites cEntity = new Entites();
                            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                            String strColor = warn.getColor();
                            String colors = "";
                            switch (strColor) {
                                case "蓝色":
                                    colors = ColorUtil.Color2String(Color.BLUE);
                                    break;
                                case "黄色":
                                    colors = ColorUtil.Color2String(Color.YELLOW);
                                    break;
                                case "橙色":
                                    colors = ColorUtil.Color2String(Color.ORANGE);
                                    break;
                                case "红色":
                                    colors = ColorUtil.Color2String(Color.RED);
                                    break;
                            }
                            // 16进制颜色
                            cEntity.setColor(colors);
                            String[] dotset = pos.split(";");
                            DmMapPoint[] points = new DmMapPoint[dotset.length];
                            Integer index = 0;
                            for (String strDot : dotset) {
                                String[] dot = strDot.split(" ");
                                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                                MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                                tempPos.add(dm);
                                points[index] = dmDot;
                                index++;
                            }
                            MapCommon dmMapCom = new MapCommon();
                            int[] parts = new int[1];
                            parts[0] = points.length;
                            DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
                            DmMapPoint ltDotCenter = transformService.LambertConvertToLonLat(dmdotCenter.x, dmdotCenter.y);
                            lon = ltDotCenter.x;
                            lat = ltDotCenter.y;
                            cEntity.setPosArr(tempPos);
                            entites.add(cEntity);
                        } catch (Exception e) {
                            System.err.println(e.getStackTrace());
                        }
                    }
                }
                warn.setTime(new DateTime(warn.getAnnouncedtime()).toDateTimeString());

                Warning nwarning = new Warning();// 总
                nwarning.setEntites(entites);
                nwarning.setPos(warn.getPos());
                resultList.add(nwarning);
            }
        } else if (type.equals("地质灾害")) {
            List<DZWarning> result = new ArrayList<DZWarning>();
            if (!bindid.equals("")) {
                result = tourService.getDzpart(bindid);// 查询地质灾害预警区
            }
            for (DZWarning dzWarning : result) {
                if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                    dzWarning.setWarLevel("蓝色预警");
                }
                if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                    dzWarning.setWarLevel("黄色预警");
                }
                if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                    dzWarning.setWarLevel("橙色预警");
                }
                if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                    dzWarning.setWarLevel("红色预警");
                }
                ArrayList<Entites> entites = new ArrayList<Entites>();
                if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                    String[] posArr = dzWarning.getPos().split("\\*");
                    for (String pos : posArr) {
                        try {
                            if (pos == null || pos.equals("")) {
                                continue;
                            }
                            Entites entity = new Entites();
                            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                            String strColor = pos.split("#")[0];
                            entity.setColor(strColor);
                            String[] dotset = pos.split("#")[1].split(",");
                            for (String strDot : dotset) {
                                String[] dot = strDot.split(" ");
                                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                                MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                                tempPos.add(dm);
                            }
                            entity.setPosArr(tempPos);
                            entites.add(entity);
                        } catch (Exception e) {
                            System.err.println(e.getStackTrace());
                        }
                    }
                    dzWarning.setPos(dzWarning.getPos());
                }
                Date date = dzWarning.getDateChar();
                dzWarning.setDate(new DateTime(date).toDateString());
                dzWarning.setDateChar(null);

                Warning nwarning = new Warning();// 总
                nwarning.setGradeArea3(dzWarning.getGradeArea3());
                nwarning.setGradeArea4(dzWarning.getGradeArea4());
                nwarning.setGradeArea5(dzWarning.getGradeArea5());
                nwarning.setWarntype(dzWarning.getWarntype());
                nwarning.setDocpath(dzWarning.getDocpath());
                nwarning.setDateChar(dzWarning.getDate());
                nwarning.setDocid(dzWarning.getDocid());
                nwarning.setEntites(entites);
                nwarning.setPos(dzWarning.getPos());
                resultList.add(nwarning);
            }
        } else if (type.equals("森林火险")) {
            List<HXYJ_Warning> result = new ArrayList<HXYJ_Warning>(); //
            if (!bindid.equals("")) {
                selectKey.setDocid(bindid);
                result = forestryfcstService.getFirewarning(selectKey);// 查询森林火险预警区
            }
            String time = "";
            for (HXYJ_Warning warning : result) {
                if (warning.getGradeArea2() != null && !warning.getGradeArea2().equals("")) {
                    warning.setWarntype("蓝色预警");
                }
                if (warning.getGradeArea3() != null && !warning.getGradeArea3().equals("")) {
                    warning.setWarntype("黄色预警");
                }
                if (warning.getGradeArea4() != null && !warning.getGradeArea4().equals("")) {
                    warning.setWarntype("橙色预警");
                }
                if (warning.getGradeArea5() != null && !warning.getGradeArea5().equals("")) {
                    warning.setWarntype("红色预警");
                }
                ArrayList<Entites> entites = new ArrayList<Entites>();
                time = warning.getDateChar().toString();
                Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(time);
                // 格式化
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String sDate = sdf.format(date);// 时间

                if (!StringUtil.IsNullOrEmpty(warning.getPos())) {
                    String[] posArr = warning.getPos().split("\\*");
                    DmMapPoint[] points = null;
                    for (String pos : posArr) {
                        try {
                            if (pos == null || pos.equals("")) {
                                continue;
                            }
                            Entites entity = new Entites();// 实体类：颜色，坐标
                            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                            String strColor = pos.split("#")[0];
                            entity.setColor(strColor);
                            String[] dotset = pos.split("#")[1].split(",");
                            Integer index = 0;
                            points = new DmMapPoint[dotset.length];
                            for (String strDot : dotset) {
                                String[] dot = strDot.split(" ");
                                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                                MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                                tempPos.add(dm);
                                points[index] = dmDot;
                                index++;
                            }
                            entity.setPosArr(tempPos);
                            entites.add(entity);
                        } catch (Exception e) {
                            System.err.println(e.getStackTrace());
                        }
                    }
                    Warning nwarning = new Warning();// 总
                    nwarning.setGradeArea3(warning.getGradeArea3());
                    nwarning.setGradeArea4(warning.getGradeArea4());
                    nwarning.setGradeArea5(warning.getGradeArea5());
                    nwarning.setWarntype(warning.getWarntype());
                    nwarning.setDocpath(warning.getDocpath());
                    nwarning.setDateChar(sDate);
                    nwarning.setDocid(warning.getDocid());
                    nwarning.setEntites(entites);
                    nwarning.setDpart(points);
                    nwarning.setPos(warning.getPos());
                    resultList.add(nwarning);
                }
            }
        }
        return resultList;
    }

    /**
     * 空气污染
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showAirzhishu")
    @ResponseBody
    public Object showAirzhishu(HttpServletRequest request, Model model) {
        List<Map<String, Object>> resultList = tourService.showAirzhishu();
        String index = "空气污染气象条件";
        String result = "";
        if (resultList != null && resultList.size() > 0) {
            result = resultList.get(0).get("datechar").toString().substring(0, 10);
            Map<String, String> zs = DbConfig.getZhiShuType();
            for (Map<String, Object> map : resultList) {
                Iterator<Entry<String, String>> iterator = zs.entrySet().iterator();
                Entry<String, String> entry;
                while (iterator.hasNext()) {
                    entry = iterator.next();
                    String zhishu = entry.getValue();
                    if (zhishu.equals(index)) {
                        String key = entry.getKey();
                        String level = map.get(key + "grade").toString();
                        String note = map.get(key + "text").toString();
                        result += map.get("cityname") + note + ";";
                    }
                }
            }
        }
        if (result.endsWith(";")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }


    /**
     * 景观预报
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showJGForecast")
    @ResponseBody
    public Object showJGForecast(HttpServletRequest request, Model model) {
        String staId = request.getParameter("staId");
        List<special_fcst> resultList = tourService.showJGForecast(staId);
        String result = "";
        if (resultList != null && resultList.size() > 0) {
            for (special_fcst sp : resultList) {
                result += sp.getTypename() + "：" + sp.getSuitable() + "</br>";
            }
        }
        return result;
    }




    @RequestMapping("/Tourspecial")
    @ResponseBody
    public Object getTourspecial(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return tourService.getTouristProduct(-1, "旅游专题服务", startDate, endDate);// 查询时间段内的景点预报
    }



    @RequestMapping("/TourSpecialshowDoc")
    @ResponseBody
    public String TourSpecialshowDoc(HttpServletRequest request, Model model) {
        String servicePath = "";
        String docId = request.getParameter("docId");// 文档编号
        String fileName = request.getParameter("docName");// 文档名称
        String tableName = request.getParameter("tableName");
        String urlpath ;
        if (operatingSystem.equals("Windows")){
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\TourSpecialDoc\\";
        }else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/TourSpecialDoc/";
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String docType = fileName.split("\\.")[fileName.split("\\.").length - 1];
        // 判断文件类型是否是word
        if (docType.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(docType, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\TourSpecialDoc\\" + fileName.replace(docType, "pdf");
                }else {
                    servicePath = "Temp/TourSpecialDoc/" + fileName.replace(docType, "pdf");
                }

            } else {
                // 从mongdo中获取文件
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", docId);
                map.put("table_name", tableName);
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                // 本地文件
                try {
                    if (operatingSystem.equals("Windows")){
                        servicePath = "Temp\\TourSpecialDoc\\" + fileName.replace(docType, "pdf");
                    }else {
                        servicePath = "Temp/TourSpecialDoc/" + fileName.replace(docType, "pdf");
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }



    /**
     * 通过AB点经纬度获取距离
     *
     * @param pointA A点(经，纬)
     * @param pointB B点(经，纬)
     * @return 距离(单位 ： 米)
     */
    Double getDistance(Point2D pointA, Point2D pointB) {
        double EARTH_RADIUS = 6371393; // 平均半径,单位：m
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(pointA.getX()); // A经弧度
        double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度
        double radiansBX = Math.toRadians(pointB.getX()); // B经弧度
        double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
                + Math.sin(radiansAY) * Math.sin(radiansBY);
        double acos = Math.acos(cos); // 反余弦值
        return EARTH_RADIUS * acos; // 最终结果
    }

    public static DmMapRectangle getObjRect(DmMapPoint[] points) {
        DmMapRectangle rct = new DmMapRectangle();
        rct.maxX = (-Double.MAX_VALUE);
        rct.maxY= (-Double.MAX_VALUE);
        rct.minX = (Double.MAX_VALUE);
        rct.minY = (Double.MAX_VALUE);
            for (int j = 0; j < points.length; j++) {
                DmMapPoint dt = points[j];
                if (dt.x < rct.minX)
                    rct.minX = dt.x;
                if (dt.x > rct.maxX) {
                    rct.maxX = dt.x;
                }
                if (dt.y < rct.minY) {
                    rct.minY = dt.y;
                }
                if (dt.y > rct.maxY)
                    rct.maxY = dt.y;
        }
        return rct;
    }
}
